package com.mmall.concurrency.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class SynchronizedExample2 {

    //修饰一个代码块
    public void test1()
    {
        synchronized (SynchronizedExample2.class)
        {
            for (int i = 0; i < 10; i++)
            {
                log.info("【对象级同步代码块】test1 - {}",i);
            }
        }
    }

    // 修饰一个方法
    public synchronized void test2()
    {
        for (int i= 0; i < 10; i++)
        {
            log.info("【对象级同步方法】test1 - {}",i);
        }
    }

    public static void main(String[] args) {
        //ctrl +alt + v
        SynchronizedExample2 example1 = new SynchronizedExample2();
        //创建线程池方式一：非手动创建 newCachedThreadPool可能存在创建的线程池过多；不推荐
        ExecutorService executorService = Executors.newCachedThreadPool();
        //测试同步代码块
        /*executorService.execute(()->{
            example1.test1();
        });
        executorService.execute(()->{
            example1.test1();
        });*/
        //测试同步方法
        executorService.execute(()->{
            example1.test2();
        });
        executorService.execute(()->{
            example1.test2();
        });

        //创建线程池方式二：手动创建线程池；推荐
        /*ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 10, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2));
        threadPoolExecutor.execute(()->{
            example1.test1();
        });
        threadPoolExecutor.execute(()->{
            example1.test1();
        });*/
    }

}
